<!--这是一个函数式渲染组件，不需要template标签，setup函数将返回一个render函数-->
<!--所有（可能）包含异步属性的ViewUnit都不应该直接使用，请包裹ViewSkeleton处理-->
<!--此处的option应该是存粹的vnode配置Object对象, props中不再存在领域驱动语法-->
<script>
import {ref, h, onBeforeMount, onMounted, onErrorCaptured} from 'vue';
import {transVnode} from "./defaultRule/RenderRule.js"

  export default {
    props: {
      option: Object,
      dataScope: Object,
      refScope: Object,
      funcScope: Object,
      slotScope: Object,
      uuid: String
    },
    setup(props, context) {
      const ready = ref(false)
      const El = ref()
      const errorLog = ref('')
      const transOption = ref()
      function renderUnit(vnode) {
        transOption.value = transVnode(vnode, {...props, ...context}) // 这一步是很重要的ref数据装饰的过程
        const unitOption = transOption.value
        const refScope = props.refScope
        refScope[props.uuid] = El
        if (unitOption.type) {
          return h(unitOption.type, {...unitOption.props, ref: El, allScope: {dataScope: props.dataScope, slotScope: props.slotScope}, uuid: props.uuid}, unitOption.children)
        }
      }

      onErrorCaptured((e,i,s) => {
        console.error(e)
        errorLog.value = e.toString()
        ready.value = false
        return false
      })

      onBeforeMount(async () => {
        ready.value = true
      })

      onMounted(() => {
        if (props.option.props?.onMounted) {
          const func = transVnode(props.option.props?.onMounted, {...props, ...context})
          if(func instanceof Function) {
            func()
          }
        }
      })

      // 返回渲染函数
      return () => {
        return ready.value ? renderUnit(props.option) : h('div', {style: {fontSize: '12px'}} ,errorLog.value || 'loading');
      }
    }
  }
</script>

<style scoped></style>
